package fragment;

import java.util.ArrayList;
import java.util.List;

import com.android.volley.VolleyError;
import com.qzhy.female.R;

import Constant.Constance;
import activity.PostDetailActivity;
import adapter.PrPostAdapter;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import model.Articles;
import model.Category_Result;
import utils.GsonUtils;
import utils.HTTPUtils;
import volley.VolleyListener;
import widget.MyListView;
import widget.MyListView.onRefreshListener;

/**
 * A simple {@link Fragment} subclass.
 *
 */
public class HomeFragment extends BaseFragment implements OnClickListener
{

	private ImageView mImgUser;
	private MyListView mPrListview;
	private PrPostAdapter prAdapter;
	ArrayList<Category_Result>  mArticles=new ArrayList<Category_Result>();
	private ImageView mImgSearch;
	private int Pageindex=2;
	public HomeFragment() {
		// Required empty public c1onstructor
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_home, null);
		return view;
	}
	/**
	 * 返回的时候被调用
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.i("生命周期", "onActivityCreated");
		super.onActivityCreated(savedInstanceState);
		GetDate();
		InitUI(view);
	}



	private void GetDate() {
//		showLoadingDialog();
        GetPostDate();
	}

	private void GetPostDate() {
		HTTPUtils.get(getContext(), Constance.URL.POST_ARTICLE,new VolleyListener() {
			@Override
			public void onResponse(String arg0) {
//				Toast.makeText(getContext(), "帖子详情"+arg0.toString(), 1).show();
				Log.i("帖子详情", arg0.toString());
				Articles articles = GsonUtils.parseJSON(arg0, Articles.class);
				String status = articles.getStatus();
				if(status.equals("success")){
					dismissLoadingDialog();
					List<Category_Result> result = articles.getResult();
					mArticles.clear();
					mArticles.addAll(result);
					prAdapter.notifyDataSetChanged();
				}else {
					showLoadingDialog();
				}
			}
			
			@Override
			public void onErrorResponse(VolleyError arg0) {
				Toast.makeText(getContext(), "解析错误"+arg0.toString(), 1).show();
			}
		});
	}

	private void InitUI(View view) {
		mImgUser = (ImageView) view.findViewById(R.id.img_user);
		mImgSearch = (ImageView) view.findViewById(R.id.img_search);
		mImgSearch.setOnClickListener(this);
		mImgUser.setOnClickListener(this);
		mPrListview = (MyListView) view.findViewById(R.id.ptrListView);
		prAdapter = new PrPostAdapter(getActivity(),mArticles);
		mPrListview.setAdapter(prAdapter);
		mPrListview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//				Toast.makeText(getContext(), "ID:"+mArticles.get(position).getId(), Toast.LENGTH_SHORT).show();
				if(position<=prAdapter.getCount()){
					Intent intent = new Intent(getActivity(),PostDetailActivity.class);
					intent.putExtra("AriticleId", mArticles.get(position-1).getId());
					startActivity(intent);
				}
			}
		});
		mPrListview.setOnRefreshListener(new onRefreshListener() {
			@Override
			public void refresh() {
				new Refresh().execute();
			}
			
			@Override
			public void loadMore() {
				new LoadMore().execute();
			}
		});
	}

	private class Refresh extends AsyncTask<Void, Void, String> {
		protected String doInBackground(Void... params) {
			try {
				Thread.sleep(1000);
				GetPostDate();
			} catch (InterruptedException e) {
			}
			return "";
		}
		protected void onPostExecute(String result) {
			mPrListview.onRefreshComplete();
		}
	}
	
	private class LoadMore extends AsyncTask<Void, Void, String> {
		protected String doInBackground(Void... params) {
			try {
				Thread.sleep(2000);
				getMore();
			} catch (InterruptedException e) {
			}
			return "";
		}
		protected void onPostExecute(String result) {
			mPrListview.onRefreshComplete();
		}
	}
	private void getMore() {
//		Toast.makeText(getContext(), "加载页:"+Pageindex, 1).show();
		HTTPUtils.get(getContext(), Constance.URL.POST_ARTICLE+"/?page="+Pageindex, new VolleyListener() {
			@Override
			public void onResponse(String arg0) {
				Articles articles = GsonUtils.parseJSON(arg0, Articles.class);
				String status = articles.getStatus();
				if(status.equals("success")){
					Pageindex++;
					List<Category_Result> result = articles.getResult();
					if(result.size()==0){
//						getMore();
					}else {
						dismissLoadingDialog();
						prAdapter.addItem(result);
						prAdapter.notifyDataSetChanged();
					}
				}
			}
			@Override
			public void onErrorResponse(VolleyError arg0) {
				Toast.makeText(getContext(), arg0.toString(), 1).show();
			}
		});
	}
	@Override
	public void onDestroy() {
		dismissLoadingDialog();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_user:
			break;
		case R.id.img_search:
			break;
		default:
			break;
		}
	}
	private View view;
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		Log.i("生命周期", "onDestroyView");
		Bundle outState=null;
		onSaveInstanceState(outState);
		super.onDestroyView();
	}
	@Override
	public void onSaveInstanceState(Bundle outState) {
		Log.i("生命周期", "onSaveInstanceState");
		super.onSaveInstanceState(outState);
	}
}
